import React from 'react';
import { withLeaflet } from 'react-leaflet';
import classNames from 'classnames/bind';
import { Button } from 'antd';
import { lContext } from '../index';
import deleteImg from './img/delete.png';
import styles from './index.less';
import setting from './setting';

const classes = classNames.bind(styles);

class LSelect extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      latlngs: [], // 鼠标起始点坐标
      isMove: false,
      selectType: 'circle',
      originCenter: '',
      drawArr: [] // 存放所有标记的数组画图数据
    };

    const { fields, action: { active } } = props.events.click;
    if (active) {
      const selectParam = fields.selectParam.value === undefined ? '' : fields.selectParam.value;
      this.setDataPool({ selectParam });
    }
  }

  componentWillMount() {
    const { leaflet: { map } } = this.props;

    // 监听地图的事件
    map.on('mousedown', this.onmouseDown);
    map.on('mousemove', this.onMove);
    map.on('mouseup', this.onmouseUp);
    map.on('contextmenu', this.onContextmenu);
  }

  static setting = setting;

  onmouseDown = (e) => {
    const { leaflet: { map } } = this.props;
    const { latlngs } = this.state;
    const originCenter = e.latlng;
    this.setState({ originCenter });
    if (typeof this.tmprec !== 'undefined') {
      this.tmprec.remove();
    }
    // 左上角坐标
    latlngs[0] = [e.latlng.lat, e.latlng.lng];
    // 开始绘制，监听鼠标移动事件
    map.on('mousemove', this.onMove);
  }

   onMove = (e) => {
     const { leaflet: { map } } = this.props;
     const { latlngs } = this.state;
     const { isMapDrag } = this.context;
     latlngs[1] = [e.latlng.lat, e.latlng.lng];
     if (!isMapDrag && latlngs) {
       this.setState({ isMove: true, isShowInput: true });
       this.drawRectangleLine(latlngs, map);
       this.drawCircleLine(map, e);
     }
   }

    onContextmenu = (rId, mapId) => {
      const { leaflet: { map } } = this.props;
      const { drawArr } = this.state;
      const tempList = [];
      drawArr.forEach(item => {
        if (item.id === rId) { // _leaflet_id
          map.removeLayer(item.marker);
        }
        if (item.id === mapId) {
          map.removeLayer(item.marker);
        }
        if (item.id !== rId && item.id !== mapId) {
          tempList.push(item);
        }
      });
      const postData = tempList.filter(it => it.type !== 'delIcon').map((item) => {
        const arr = [];
        if (item.type === 'circle') {
          const cirObj = {
            type: item.type,
            id: item.id,
            radius: item.radius,
            latlng: item.latlng,
          };
          arr.push(cirObj);
        }
        if (item.type === 'rectangle') {
          const rectObj = {
            type: item.type,
            id: item.id,
            bounds: item.bounds
          };
          arr.push(rectObj);
        }
        return arr;
      });
      this.setState({
        drawArr: tempList
      });
      this.setDataPool({ selectParam: window.JSON.stringify(postData) });
    }

   drawRectangleLine = (latlngs, map) => {
     const { selectType } = this.state;
     if (selectType === 'rectangle') {
     // 删除临时矩形
       if (typeof this.tmprect !== 'undefined') this.tmprect.remove();
       // 添加临时虚线矩形
       this.tmprect = L.rectangle(latlngs, { dashArray: 5 }).addTo(map);
     }
   }

   drawCircleLine = (map, e) => {
     const { selectType, originCenter, latlngs } = this.state;
     if (selectType === 'circle') {
       const r = L.latLng(e.latlng).distanceTo(originCenter);
       // 删除临时圆形
       if (typeof this.tmprect !== 'undefined') this.tmprect.remove();
       // 添加临时圆形
       this.tmprect = L.circle(latlngs[0], { radius: r, dashArray: 5 }).addTo(map);
     }
   }

  onmouseUp = (e) => {
    const { leaflet: { map } } = this.props;
    const {
      latlngs, selectType, originCenter, drawArr
    } = this.state;
    const drawArrTemp = _.cloneDeep(drawArr);
    const { isMapDrag, switchMapDrag } = this.context;
    // 矩形绘制完成，停止监听鼠标移动事件
    map.off('mousemove');
    // 右下角坐标
    latlngs[1] = [e.latlng.lat, e.latlng.lng];
    if (!isMapDrag && selectType === 'rectangle') {
      const {
        config: {
          rectangle: {
            bgColor, lineColor, lineWidth
          }
        }
      } = this.props;
      // 绘制实际矩形
      this.rectangle = L.rectangle(latlngs, {
        color: lineColor,
        fillColor: bgColor,
        fillOpacity: 0.2,
        weight: lineWidth,
      });
      map.addLayer(this.rectangle);
      // eslint-disable-next-line camelcase
      const { _leaflet_id, _bounds } = this.rectangle;
      const rectObj = {
        type: 'rectangle',
        id: _leaflet_id,
        bounds: _bounds,
        marker: this.rectangle
      };
      if (this.rectangle) {
        drawArrTemp.push(rectObj);
      }
      // 将所有圈选图层成组
      // this.layerGroup = L.layerGroup(layers);
      // map.addLayer(this.layerGroup);

      const myIcon = L.icon({
        iconUrl: deleteImg,
        iconSize: [30, 30],
        // iconAnchor: [15, 40]
      });
      // 增加关闭marker
      const lat = latlngs[0][0] - ((latlngs[0][0] - latlngs[1][0]) / 2);
      const lng = latlngs[0][1] + ((latlngs[1][1] - latlngs[0][1]) / 2);
      map.marker = L.marker(
        [lat, lng], { icon: myIcon }
      );
      // .bindTooltip('关闭圈选', {
      //   className: 'distanceTool',
      //   direction: 'right',
      //   offset: L.point(16, -25)
      // });
      map.addLayer(map.marker);
      const { _leaflet_id: mapId } = map.marker;
      const markerObj = {
        type: 'delIcon',
        id: mapId,
        marker: map.marker,
      };
      if (map.marker) {
        drawArrTemp.push(markerObj);
      }
      map.marker.on('click', () => this.onContextmenu(_leaflet_id, mapId));
      this.setState({
        drawArr: drawArrTemp
      });
      const postData = drawArrTemp.filter(item => item.type === 'rectangle' || item.type === 'circle').map((item) => {
        const arr = [];
        if (item.type === 'circle') {
          const cirObj = {
            type: item.type,
            id: item.id,
            radius: item.radius,
            latlng: item.latlng,
          };
          arr.push(cirObj);
        }
        if (item.type === 'rectangle') {
          const recObj = {
            type: item.type,
            id: item.id,
            bounds: item.bounds
          };
          arr.push(recObj);
        }
        return arr;
      });
      this.setDataPool({ selectParam: JSON.stringify(postData) });
    }
    if (!isMapDrag && selectType === 'circle') {
      // 计算半径， 单位（米）
      const r = L.latLng(e.latlng).distanceTo(originCenter);
      const {
        config: {
          circle: {
            bgColor, lineColor,
            lineWidth, type
          }
        }
      } = this.props;

      const dashArray = type === 'solid'
        ? []
        : type === 'dashed'
          ? [2 * lineWidth, 2 * lineWidth]
          : [0, 2 * lineWidth];
      const lineCap = type === 'dashed' ? 'butt' : 'round';

      // 绘制圆
      // map.tempCircle = new L.Circle();
      const id = new Date().getTime();
      const circleTemp = new L.Circle();
      /* eslint-disable no-underscore-dangle */
      circleTemp._leaflet_id = id;
      map.tempCircle = circleTemp;
      map.tempCircle.setLatLng(originCenter);
      map.tempCircle.setRadius(r);
      map.tempCircle.setStyle({
        color: lineColor,
        fillColor: bgColor,
        weight: lineWidth,
        fillOpacity: 1,
        dashArray,
        lineCap
      });

      const myIcon = L.icon({
        iconUrl: deleteImg,
        iconSize: [30, 30],
        // iconAnchor: [15, 40]
      });

      // 增加关闭marker
      map.marker = L.marker(
        latlngs[0], { icon: myIcon }
      ).addTo(map);
      // eslint-disable-next-line camelcase
      const { _leaflet_id, _mRadius, _latlng } = circleTemp;
      const { _leaflet_id: mapId } = map.marker;

      const markerObj = {
        type: 'delIcon',
        id: mapId,
        marker: map.marker,
      };

      // 添加删除的marker到容器
      if (map.marker) {
        drawArrTemp.push(markerObj);
      }

      map.marker.on('click', () => this.onContextmenu(_leaflet_id, mapId));
      map.addLayer(map.tempCircle);

      const circleObj = {
        type: 'circle',
        id: _leaflet_id,
        radius: _mRadius,
        latlng: _latlng,
        marker: map.tempCircle
      };
      if (map.tempCircle) {
        drawArrTemp.push(circleObj);
      }

      // 将所有圈选图层成组
      const drawArrTempMap = drawArrTemp.map(it => it.marker);
      this.layerGroup = L.layerGroup(drawArrTempMap);
      map.addLayer(this.layerGroup);

      this.setState({
        drawArr: drawArrTemp
      });
      const postData = drawArrTemp.filter(item => item.type === 'circle' || item.type === 'rectangle').map((item) => {
        const arr = [];
        if (item.type === 'circle') {
          const cirObj = {
            type: item.type,
            id: item.id,
            radius: item.radius,
            latlng: item.latlng,
          };
          arr.push(cirObj);
        }
        if (item.type === 'rectangle') {
          const rectObj = {
            type: item.type,
            id: item.id,
            bounds: item.bounds
          };
          arr.push(rectObj);
        }
        return arr;
      });
      this.setDataPool({ selectParam: window.JSON.stringify(postData) });
    }

    switchMapDrag(true);

    if (this.tmprect) map.removeLayer(this.tmprect);
  }

  // 清除所有圈选
  handleClear =() => {
    if (this.layerGroup != null) this.layerGroup.clearLayers();
    const { leaflet: { map } } = this.props;
    const { drawArr } = this.state;
    drawArr.forEach(item => {
      map.removeLayer(item.marker);
    });
    this.setState({
      drawArr: []
    });
    this.setDataPool({ selectParam: JSON.stringify([]) });
  }

  // 更新store中的dataPoll
  setDataPool(dataPoll) {
    const {
      bigScreen: { setDataPool },
      events: { click }, path, editable
    } = this.props;

    setDataPool(click, dataPoll, path, editable);
  }

  render() {
    const { isMapDrag, switchMapDrag } = this.context;
    const {
      config: {
        btn: {
          font, backgroundColor, right, top
        },
        clearAll: {
          clearTop, clearRight, clearBgColor, clearFont
        }
      },
    } = this.props;
    const btnStyle = {
      ...font,
      backgroundColor,
      top: +top,
      right: +right
    };
    const clearBtnStyle = {
      ...clearFont,
      backgroundColor: clearBgColor,
      top: +clearTop,
      right: +clearRight
    };
    const btn = {
      ...font
    };
    return (
      <React.Fragment>
        <div
          className={classes('areaFilter')}
          style={btnStyle}
        >
          <Button
            className={styles.circleBtn}
            onClick={
            () => {
              this.setState({ selectType: 'circle' });
              switchMapDrag(!isMapDrag);
            }}
            style={btn}
            >
            圆形
          </Button>
          <Button
            onClick={
            () => {
              this.setState({ selectType: 'rectangle' });
              switchMapDrag(!isMapDrag);
            }}
            style={btn}
            >
            矩形
          </Button>
        </div>
        <div
          className={classes('areaFilter')}
          style={clearBtnStyle}
          onClick={() => this.handleClear()}
        >
          清除全部
        </div>
      </React.Fragment>
    );
  }
}
LSelect.contextType = lContext;
export default withLeaflet(LSelect);
